import 'package:flutter/material.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:intl/intl.dart';

part 'home_notice_model.g.dart';

enum NoticeType {
  // 新闻
  news,
  // 公告
  announcement,
  // 个人
  personal;

  String get label {
    switch (this) {
      case NoticeType.news:
        return '新闻';
      case NoticeType.announcement:
        return '公告';
      case NoticeType.personal:
        return '个人';
    }
  }

  Color get color {
    switch (this) {
      case NoticeType.news:
        return Colors.blue;
      case NoticeType.announcement:
        return Colors.orange;
      case NoticeType.personal:
        return Colors.green;
    }
  }
}

// 消息类型转枚举
class NoticeTypeConverter implements JsonConverter<NoticeType, int> {
  const NoticeTypeConverter();

  @override
  NoticeType fromJson(int json) {
    switch (json) {
      case 1:
        return NoticeType.news;
      case 2:
        return NoticeType.announcement;
      case 3:
        return NoticeType.personal;
      default:
        return NoticeType.news;
    }
  }

  @override
  int toJson(NoticeType object) {
    switch (object) {
      case NoticeType.news:
        return 1;
      case NoticeType.announcement:
        return 2;
      case NoticeType.personal:
        return 3;
    }
  }
}

// 日期时间转字符串
class DateTimeConverter implements JsonConverter<String, String> {
  const DateTimeConverter();

  @override
  String fromJson(String json) {
    if (json.isEmpty) {
      return '';
    }
    DateTime dateTime = DateTime.tryParse(json) ?? DateTime.now();
    return DateFormat('MM-dd').format(dateTime);
  }

  @override
  String toJson(String object) {
    return object;
  }
}

@JsonSerializable(includeIfNull: false)
class HomeNoticeModel {
  HomeNoticeModel(this.id, this.type, this.content, this.updateTime);

  @JsonKey(defaultValue: 0)
  int id;
  @NoticeTypeConverter()
  NoticeType type;
  @JsonKey(defaultValue: '')
  String content;
  @DateTimeConverter()
  @JsonKey(defaultValue: '')
  String updateTime;

  factory HomeNoticeModel.fromJson(Map<String, dynamic> json) =>
      _$HomeNoticeModelFromJson(json);
  Map<String, dynamic> toJson() => _$HomeNoticeModelToJson(this);
}
